//
//  Util.m
//  Cloud189
//
//  Created by Liam on 11-10-27.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "Util.h"
#import "CmnFunc.h"
#import "LocalURLCache.h"
#import <arpa/inet.h>
#import <net/if.h>
#import <ifaddrs.h>
#import <net/if_dl.h>
#import "UserManager.h"
#import "YoucAppAppDelegate.h"
#import <iOSToast.h>
#import <YoucApiError.h>

@implementation Util

+ (UIViewController*)viewController:(UIView *)view
{
	UIResponder * nextResponder = [view nextResponder]; 
	if ([nextResponder isKindOfClass:[UIViewController class]])
	{ 
		return (UIViewController*)nextResponder;
	}
	
	return nil;
}

+ (UIViewController*)rootViewController
{
	UIViewController *rootViewController = nil;
	
	UIWindow * main = [Util mainWindow];
	if (main)
	{
        rootViewController = main.rootViewController;
		if (!rootViewController)
		{
			if ([[main subviews] count])
			{
				UIView * view = nil;
				for (view in [main subviews])
				{
					if (view)
					{
						rootViewController = [Util viewController:view];
						if (rootViewController)
							break;
					}
				}
			}
		}
    }
	return rootViewController;
}

//static UIViewController* g_mainViewController = nil;
//
//+ (UIViewController*)mainViewController
//{ 
//	return g_mainViewController;
//}
//
//+ (void)setMainViewController:(UIViewController*)viewController
//{
//	g_mainViewController = viewController;
//}

+ (UIWindow*)mainWindow
{
	YoucAppAppDelegate* delegate = (YoucAppAppDelegate*)[UIApplication sharedApplication].delegate;
	
	return delegate.window;
}

+ (void)showToastIfNeededWithAPIError:(NSError *)error
{
	switch ([error code])
	{
		case YoucApiErrorRequestTimeOut:
		case YoucApiErrorNoConnection:
			[[Util mainWindow] makeToast:@"网络连接失败" duration:1.5f position:kDefaultPosition];
			break;
		default:
			break;
	}
}

//+ (NSString *)currentUserDocumentDirectory
//{
//    NSString *dir = [NSString stringWithFormat:@"%@/%@", [CmnFunc getPrivateDocumentDirectory], [[UserManager instance] getSavedLoginName] ];
//	
//	if ([[NSFileManager defaultManager] fileExistsAtPath:dir] == NO)
//	{
//		[[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
//	}
//    
//	return dir;
//}

+ (NSString *)appDataDirectory
{
	NSString *dir = [NSString stringWithFormat:@"%@/.appdata", [CmnFunc getCachesDirectory]];
	
	if([[NSFileManager defaultManager] fileExistsAtPath:dir] == NO)
	{
		[[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
	}

	return dir;
}

+ (NSString *)currentUserAppDataDirectory
{
	NSString *dir = [NSString stringWithFormat:@"%@/%@", [Util appDataDirectory], SAFE_FORMAT_STRING([[UserManager instance] getSavedLoginName])];
	
	if ([[NSFileManager defaultManager] fileExistsAtPath:dir] == NO)
	{
		[[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
	}
    
	return dir;
}

//+ (void)clearCache
//{
//	[[DownloadManager instance] releaseSpaces];
//	[[LocalURLCache sharedLocalURLCache] clearCache];
//}
//
//+ (void)clearAppData
//{
//	[[FileSystemManager instance] clearCache];
//	[[DownloadManager instance] removeAll];
//	[[UploadManager instance] removeAll];
//}
//
//+ (UIAlertView *)showAlert:(NSString *)message withTitle:(NSString *)title cancelButtonTitle:(NSString *)cancelButtonTitle
//{
//	UIAlertView * alertView = [[[UIAlertView alloc] initWithTitle:title ? title : @"提示"
//														 message:message
//														delegate:nil
//											   cancelButtonTitle:cancelButtonTitle
//											   otherButtonTitles:nil] autorelease];
//	
//	[alertView show];
//	return alertView;
//}
//
//+ (UIAlertView *)showAlert:(NSString *)message withTitle:(NSString *)title
//{
//	return [Util showAlert:message withTitle:title cancelButtonTitle:@"确定"];
//}
//
//long long llGB = 1024 * 1024 * 1024;
//+ (long long)GBFromLonglongBytes:(long long)bytes
//{
//	return (bytes / llGB);
//}
//
//+ (double)GBFromFloatBytes:(double)bytes;
//{
//	return (bytes / llGB);
//}
//
//+ (double)ratioForUsedSpace:(long long)used forCapacity:(long long)capacity
//{
//	return capacity > 0 ? ((double)used / capacity) : 0.0; 
//}
//
//+ (BOOL)viewController:(UIViewController *)viewController shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
//{
//	if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
//		return (UIInterfaceOrientationIsLandscape(interfaceOrientation));
//	else
//		return (interfaceOrientation == UIInterfaceOrientationPortrait);
//}
//
//#ifndef __IPHONE_6_0
//#define __IPHONE_6_0 60000
//#endif
//
//#if (__IPHONE_OS_VERSION_MAX_ALLOWED < __IPHONE_6_0)
//typedef enum {
//    UIInterfaceOrientationMaskPortrait = (1 << UIInterfaceOrientationPortrait),
//    UIInterfaceOrientationMaskLandscapeLeft = (1 << UIInterfaceOrientationLandscapeLeft),
//    UIInterfaceOrientationMaskLandscapeRight = (1 << UIInterfaceOrientationLandscapeRight),
//    UIInterfaceOrientationMaskPortraitUpsideDown = (1 << UIInterfaceOrientationPortraitUpsideDown),
//    UIInterfaceOrientationMaskLandscape = (UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight),
//    UIInterfaceOrientationMaskAll = (UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight | UIInterfaceOrientationMaskPortraitUpsideDown),
//    UIInterfaceOrientationMaskAllButUpsideDown = (UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight),
//} UIInterfaceOrientationMask;
//#endif
//
//+ (NSUInteger)supportedInterfaceOrientationsWithController:(UIViewController *)controller
//{
//    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
//        return UIInterfaceOrientationMaskLandscape;
//    else
//        return UIInterfaceOrientationMaskPortrait;
//}
//
//+ (NSArray *)getDataCounters
//{
//    BOOL   success;
//    struct ifaddrs *addrs;
//    const struct ifaddrs *cursor;
//    const struct if_data *networkStatisc; 
//	
//    u_int32_t WiFiSent = 0;
//    u_int32_t WiFiReceived = 0;
//    u_int32_t WWANSent = 0;
//    u_int32_t WWANReceived = 0;
//	
//    NSString *name = nil;
//	
//    success = getifaddrs(&addrs) == 0;
//    if (success) 
//    {
//        cursor = addrs;
//        while (cursor != NULL) 
//        {
//            name=[NSString stringWithFormat:@"%s",cursor->ifa_name];
//            NSLog(@"ifa_name %s == %@\n", cursor->ifa_name,name);
//            // names of interfaces: en0 is WiFi ,pdp_ip0 is WWAN 
//			
//            if (cursor->ifa_addr->sa_family == AF_LINK) 
//            {
//                if ([name hasPrefix:@"en"]) 
//                {
//                    networkStatisc = (const struct if_data *) cursor->ifa_data;
//                    WiFiSent+=networkStatisc->ifi_obytes;
//                    WiFiReceived+=networkStatisc->ifi_ibytes;
//                    NSLog(@"WiFiSent %u ==%u",WiFiSent,networkStatisc->ifi_obytes);
//                    NSLog(@"WiFiReceived %u ==%u",WiFiReceived,networkStatisc->ifi_ibytes);
//                }
//				
//                if ([name hasPrefix:@"pdp_ip"]) 
//                {
//                    networkStatisc = (const struct if_data *) cursor->ifa_data;
//                    WWANSent+=networkStatisc->ifi_obytes;
//                    WWANReceived+=networkStatisc->ifi_ibytes;
//                    NSLog(@"WWANSent %u ==%u",WWANSent,networkStatisc->ifi_obytes);
//                    NSLog(@"WWANReceived %u ==%u",WWANReceived,networkStatisc->ifi_ibytes);
//                } 
//            }
//			
//            cursor = cursor->ifa_next;
//        }
//		
//        freeifaddrs(addrs);
//    }       
//	
//    return [NSArray arrayWithObjects:[NSNumber numberWithUnsignedInt:WiFiSent], [NSNumber numberWithUnsignedInt:WiFiReceived],[NSNumber numberWithUnsignedInt:WWANSent],[NSNumber numberWithUnsignedInt:WWANReceived], nil];
//}
//
//
//UIFont * getSegmentedFont(UIView * aView)
//{
//	UIFont * font = nil;
//	
//	NSString * typeName = NSStringFromClass([aView class]);
//	if ([typeName compare:@"UISegmentLabel" options:NSLiteralSearch] == NSOrderedSame) {
//		UILabel* label = (UILabel*)aView;
//		font = [[label.font retain] autorelease];
//	}
//	
//	if (!font)
//	{
//		NSArray* subs = [aView subviews];
//		NSEnumerator* iter = [subs objectEnumerator];
//		UIView* subView;
//		while ((subView = [iter nextObject]) && !font) {
//			font = getSegmentedFont(subView);
//		}
//	}
//	
//	return font;
//}
//
//
//+ (UIImage *)getSegmentedImage:(UISegmentedControl *)segmentedControl withImages:(NSArray *)images andColors:(NSArray *)colors
//{
//	NSArray * normalImages = [images objectAtIndex:0];
//	NSArray * selectedImages = [images objectAtIndex:1];
//	
//	CGFloat width = 0.0;
//	CGFloat height = 0.0;
//	
//	CGFloat scale = [UIScreen mainScreen].scale;
//	
//	NSUInteger selectedSegmentIndex = segmentedControl.selectedSegmentIndex;
//	
//	NSMutableArray * array = [NSMutableArray array];
//	
//	for (NSUInteger i=0; i < segmentedControl.numberOfSegments; i++)
//	{
//		if (i == 0)
//		{
//			[array addObject:selectedSegmentIndex == i ? [selectedImages objectAtIndex:0] : [normalImages objectAtIndex:0]];
//		}
//		else if (i == segmentedControl.numberOfSegments - 1)
//		{
//			[array addObject:selectedSegmentIndex == i ? [selectedImages objectAtIndex:[selectedImages count]-1] : [normalImages objectAtIndex:[normalImages count]-1]];
//		}
//		else
//		{
//			[array addObject:selectedSegmentIndex == i ? [selectedImages objectAtIndex:1] : [normalImages objectAtIndex:1]];
//		}
//		UIImage * image = (UIImage*)[array objectAtIndex:[array count] - 1];
//		width += image.size.width;
//		if (height < image.size.height)
//			height = image.size.height;
//	}
//	
//	if (((int)width) % 2 == 1)
//		width += 1;
//	
//	if (UIGraphicsBeginImageContextWithOptions != NULL)
//	{
//		UIGraphicsBeginImageContextWithOptions(CGSizeMake(width, height), NO, scale);
//	}
//	else
//	{
//		UIGraphicsBeginImageContext(CGSizeMake(width, height));
//	}
//	
//	CGContextRef context = UIGraphicsGetCurrentContext();
//	
//	for (NSUInteger i=0, width = 0.0; i < [array count]; i++)
//	{
//		UIImage * image = (UIImage*)[array objectAtIndex:i];
//		
//		CGRect imageRect = CGRectMake(width, 0, image.size.width, image.size.height);
//		//[image drawInRect:imageRect];
//		[image drawAtPoint:imageRect.origin];
//		
//		NSString * text = [segmentedControl titleForSegmentAtIndex:i];
//		
//		//CGContextSetShadowWithColor(context, CGSizeMake(0, 1), 1, [[UIColor whiteColor] CGColor]);
//		UIColor *textColor = selectedSegmentIndex == i ? [colors objectAtIndex:1] : [colors objectAtIndex:0];
//		CGContextSetFillColorWithColor(context, textColor.CGColor);
//		
//		UIFont * textFont = getSegmentedFont(segmentedControl);
//		CGSize textSize = [text sizeWithFont:textFont];
//		imageRect.origin.y = (imageRect.size.height - textSize.height) / 2;
//		[text drawInRect:imageRect withFont:textFont lineBreakMode:UILineBreakModeTailTruncation alignment:UITextAlignmentCenter];
//		
//		width += image.size.width;
//	}
//	
//	UIImage * viewImage = UIGraphicsGetImageFromCurrentImageContext();
//	UIGraphicsEndImageContext();
//	
//	return viewImage;
//}
//
//+ (UIImage *)imageWithName:(NSString *)imageName
//{
//	NSString * pathExtension = [imageName pathExtension];
//	NSString * pathName = [imageName stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@".%@",pathExtension] withString:@""];
//	
//	NSString* imagePath = [[NSBundle mainBundle] pathForResource:pathName ofType:pathExtension];
//	UIImage* image = [UIImage imageWithContentsOfFile:imagePath];
//	
//	return image;
//}
//
//+ (NSURL *)iconCacheURL:(NSString *)hash withSuffix:(NSString *)suffix
//{
//	NSString * iconCacheString = [NSString stringWithFormat:@"http://iconCache/%@_%@", hash, suffix];
//	return [NSURL URLWithString:iconCacheString];
//}
//
//+ (ALAsset *)assetForURL:(NSURL *)url withLibrary:(ALAssetsLibrary *)assetsLibrary
//{
//    __block ALAsset *result = nil;
//    __block NSError *assetError = nil;
//    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
//	
//    [assetsLibrary assetForURL:url resultBlock:^(ALAsset *asset) {
//        result = [asset retain];
//        dispatch_semaphore_signal(sema);
//    } failureBlock:^(NSError *error) {
//        assetError = [error retain];
//        dispatch_semaphore_signal(sema);
//    }];
//	
//	
//    if ([NSThread isMainThread]) {
//        while (!result && !assetError) {
//            [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
//        }
//    }
//    else {
//        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
//    }
//	
//    dispatch_release(sema);
//    [assetError release];
//	
//    return [result autorelease];
//}

@end
